package com.ocom.xcxapi.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.XcxApiUrl;
import com.ocom.common.entity.card.EntityXfMerchPayInfo;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.payconfig.EntityXfSignOrder;
import com.ocom.common.entity.typehandler.SignNoHandle;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.xcx.SignListVo;
import com.ocom.common.request.xcx.SignVo;
import com.ocom.common.request.xcx.SmsVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.redis.util.RedisUtil;
import com.ocom.xcxapi.client.PayConfigClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/10/18
 **/
@Slf4j
@RestController
@PreAuthorize("hasRole('ROLE_XCX')")
public class SignController {

	String url = "http://192.168.3.123:32880/ocom_pay/";
//	String url = "http://192.168.11.122:8080/ocom_pay/";

	@Autowired
	PayConfigClientService payConfigClientService;


	@Resource
	private RedisUtil redisUtil;

	@PostMapping(XcxApiUrl.URL_signList)
	public Result signList(@RequestBody SignListVo signListVo){
		return  payConfigClientService.getUserSign(signListVo.getComId(), signListVo.getPId());
	}

	@PostMapping(XcxApiUrl.URL_sms)
	public Result sms(@RequestBody SmsVo smsVo){
		EntityXfMerchPayInfo entityXfMerchPayInfo= new EntityXfMerchPayInfo();
		entityXfMerchPayInfo.setComId(smsVo.getComId());
		entityXfMerchPayInfo.setMerchId(smsVo.getMerchId());
//		entityXfMerchPayInfo.setMerchId(0);
		Result result3 = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
		log.info("签约商户信息，【{}】",result3);
		if(result3.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_3053);
		}

		EntityXfMerchPayInfo entityXfMerchPayInfo1 = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityXfMerchPayInfo.class);
		Map<String, Object> stringObjectMap = new HashMap<>();

		stringObjectMap.put("company_id", entityXfMerchPayInfo1.getCompanyId());
		stringObjectMap.put("user_name", entityXfMerchPayInfo1.getUserName());
		stringObjectMap.put("password", entityXfMerchPayInfo1.getPassword());
		stringObjectMap.put("phone", smsVo.getPhone());
		stringObjectMap.put("card_no", smsVo.getCardNo());
		stringObjectMap.put("out_trade_no", DateUtils.dateTimeNow()+RandomUtil.generateNumber(2));
		RequestUtil requestUtil = new RequestUtil();
		System.out.println(stringObjectMap);
		Map<String, String> re  = requestUtil.doPostJson(url+"icbcpay/message.do", JSON.toJSONString(stringObjectMap));
		System.out.println(re);
		Result result = JSON.parseObject(JSON.toJSONString(re),Result.class);
		log.info("短信返回，【{}】",result);

		/**
		 * {
		 * 	"code": 200,
		 * 	"msg": "success",
		 * 	"data": {
		 * 		"out_trade_no": "3805852165",
		 * 		"card_no": "6212263602105460158",
		 * 		"verify_code_no": "2022101831688462"
		 *        }
		 * }
		 */

		if(result.getCode()==200){
			Map<String,Object> map = JSON.parseObject(JSON.toJSONString(result.getData()),Map.class);
			redisUtil.set("SIGN:ICBC:"+smsVo.getPhone(),map.get("verify_code_no"),1800l);
			return ResultUtil.success();
		}
		return result;
	}

	@PostMapping(XcxApiUrl.URL_sign)
	public Result sign(@RequestBody SignVo signVo){
		EntityXfMerchPayInfo entityXfMerchPayInfo= new EntityXfMerchPayInfo();
		entityXfMerchPayInfo.setComId(signVo.getComId());
		entityXfMerchPayInfo.setMerchId(signVo.getMerchId());
//		entityXfMerchPayInfo.setMerchId(0);
		Result result3 = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
		log.info("签约商户信息，【{}】",result3);
		if(result3.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_3053);
		}

		EntityXfMerchPayInfo entityXfMerchPayInfo1 = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityXfMerchPayInfo.class);
		Map<String, Object> stringObjectMap = new HashMap<>();

		String ord = DateUtils.dateTimeNow()+RandomUtil.generateNumber(2);

		//签约单记录
		EntityXfSignOrder entityXfSignOrder = new EntityXfSignOrder();
		entityXfSignOrder.setComId(signVo.getComId());
		entityXfSignOrder.setMerchId(signVo.getMerchId());
		entityXfSignOrder.setPId(signVo.getPId());
		entityXfSignOrder.setOrderNo(ord);
		entityXfSignOrder.setBank(signVo.getIdNo());
		//TODO
		entityXfSignOrder.setSignType(signVo.getSignType());
		entityXfSignOrder.setPayWay(signVo.getPayWay());
		entityXfSignOrder.setSignNo("");
		Result result = payConfigClientService.addPaySign(entityXfSignOrder);

		log.info("调用签约/解约-返回 【{}】",result);
		if (result.getCode() != 200) {
			return ResultUtil.error(ResultEnum.Err_3051);
		}

		if(signVo.getSignType() == 1){
			stringObjectMap.put("company_id", entityXfMerchPayInfo1.getCompanyId());
			stringObjectMap.put("user_name", entityXfMerchPayInfo1.getUserName());
			stringObjectMap.put("password", entityXfMerchPayInfo1.getPassword());
			stringObjectMap.put("phone", signVo.getPhone());
			stringObjectMap.put("card_no", signVo.getCardNo());
			stringObjectMap.put("out_trade_no", ord);
			stringObjectMap.put("name", signVo.getName());
			stringObjectMap.put("id_no", signVo.getIdNo());
			stringObjectMap.put("verification_code", signVo.getVerificationCode());
			stringObjectMap.put("verify_code_no", redisUtil.get("SIGN:ICBC:"+signVo.getPhone()));

			System.out.println(stringObjectMap);
			RequestUtil requestUtil = new RequestUtil();
			Map<String, String> re  = requestUtil.doPostJson(url+"icbcpay/withholding.do", JSON.toJSONString(stringObjectMap));
			System.out.println(re);
			log.info("申请签约 参数 【】 返回 【】", stringObjectMap, re);

			/**
			 * {msg=success, code=200, data={"out_trade_no":"2022101816591087","card_no":"6212261502004763607","contract_id":"2022101283938372403607"}}
			 */

			Result result1 = JSON.parseObject(JSON.toJSONString(re),Result.class);
			log.info("签约返回，【{}】",result1);

			if(result1.getCode() ==  200){
				Map<String,Object> map = JSON.parseObject(JSON.toJSONString(result1.getData()),Map.class);
				entityXfSignOrder.setStatus(2);
				entityXfSignOrder.setSignNo(map.get("contract_id").toString());
				payConfigClientService.updatePaySign(entityXfSignOrder);
				return ResultUtil.success();
			}
			entityXfSignOrder.setStatus(3);
			payConfigClientService.updatePaySign(entityXfSignOrder);
			return result1;
		}


		//解约 查找签约

		Result result23 = payConfigClientService.getUserPayWay(signVo.getComId(),signVo.getPId(),signVo.getMerchId(),signVo.getPayWay());

		//没有需要解约的
		if(result23.getCode() !=  200){
			return ResultUtil.error(ResultEnum.Err_3068);
		}

		EntityXfSignNo entityXfSignNo = JSON.parseObject(JSON.toJSONString(result23.getData()),EntityXfSignNo.class);
		SignNoHandle signNoHandle=new SignNoHandle();

		stringObjectMap.put("company_id", entityXfMerchPayInfo1.getCompanyId());
		stringObjectMap.put("user_name", entityXfMerchPayInfo1.getUserName());
		stringObjectMap.put("password", entityXfMerchPayInfo1.getPassword());
		stringObjectMap.put("contract_id", signNoHandle.decrypt(entityXfSignNo.getSignNo(),1l));
		stringObjectMap.put("out_trade_no", ord);

		System.out.println(stringObjectMap);
		RequestUtil requestUtil = new RequestUtil();
		Map<String, String> re  = requestUtil.doPostJson(url+"icbcpay/rescind.do", JSON.toJSONString(stringObjectMap));
		System.out.println(re);
		log.info("申请签约 参数 【】 返回 【】", stringObjectMap, re);

		//【RespMachMessage{code='200', msg='success', data={"out_trade_no":"2022101817262687"}}】

		Result result1 = JSON.parseObject(JSON.toJSONString(re),Result.class);
		log.info("解约返回，【{}】",result1);

		if(result1.getCode() ==  200){
			entityXfSignOrder.setStatus(2);
			payConfigClientService.updatePaySign(entityXfSignOrder);
			return ResultUtil.success();
		}
		return result1;

	}


	//小程序 人脸 和支付 签约回调
	@PostMapping(XcxApiUrl.URL_alicallback)
	public String sign(@RequestBody HttpServletRequest request){
		log.info("----------------------request参数" + request);
		log.info("收到统一支付回调，【】",request.getParameterMap());
		return "success";
	}
}
